package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * User: haitao
 * Date: 2020/7/13
 */
@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token) {
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }
    /**
     * 显示登陆页
     *
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url,
                            Model model,
                            @CookieValue(name = "sso_token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            // 另一个系统已经登录过了，要加上token。因为系统是否登录是判断有没有token参数，如果不加上就一直死循环了。
            return "redirect:" + url + "?token=" + token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 处理登录请求
     *
     * @return
     */
    @PostMapping("/doLogin")
    public String doLogin(String username,
                          String password,
                          String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 登录成功条状，会之前的页面。
            // 把登录成功的用户保存起来
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid, username);
            // 保存该用户的token到cookie中,cookie 默认有效期是一个会话
            response.addCookie(new Cookie("sso_token", uuid));
            return "redirect:" + url + "?token=" + uuid;
        }
        // 登录失败
        return "login";
    }
}
